<template>
	<view class="page">
		<view class="nav-style" :style="{ height: navHeight + 'px' }">
			<view style="width: 50rpx; height: 100%" @click="back">
				<image class="back-img" src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/back.png" mode="aspectFit" :style="{ top: statusBarHeight + 'px' }"></image>
			</view>
			<image
				class="small-logo"
				src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/logo-white.png"
				mode="aspectFit"
				:style="{ 'padding-top': statusBarHeight + 'px' }"
			></image>
		</view>
		<view v-if="[4, 5].includes(info.step)" class="process-wrap" :style="{ 'padding-top': navHeight + 20 + 'px' }">
			<process :active="info.step" :steps="collectionStepsData" />
		</view>
		<!--    <image class="header" src="/static/image/header.png" mode="aspectHeightFit" />-->

		<view class="wrap" :style="{ 'margin-top': [1, 2, 3, 6, 7].includes(info.step) ? navHeight + 'px' : '' }">
			<test-check ref="testCheck" :info="info" :time="times" :device-number="deviceNumber" @back="back" @next="onConfirm" @Close="Shutdown" />
		</view>

		<!-- 有反应弹窗 -->
		<uni-popup ref="popup" :mask-click="false" :is-mask-click="false" type="center">
			<view class="popup-wrap">
				<!-- <image class="fixed" src="../../static/image/zixun.png" mode="" @click="skip"></image> -->
				<image class="popup-bg" src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/tips-bg.png" mode="aspectFit" />
				<view class="popup-container">
					<view class="popup-title">
						<image class="popup-img" src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/tips-icon.png" mode="aspectFit" />
						<view class="popup-text">温馨提示</view>
					</view>
					<view class="popup-content">
						您好，根据本次检测结果，您的尿液抗体筛查呈阳性。但是本次检测结果不能完全作为诊断标准，请您不必过度担忧。如您需要，疾控中心将在严格保护您的个人隐私的前提下，为您提供专业的医学咨询和确证检测。在最终结果确认前，请您不必过度担忧。即使确认阳性，通过规范的抗病毒治疗，完全可以获得与常人基本无异的寿命和生活质量。
					</view>
					<view class="popup-btn-wrap">
						<view class="popup-btn cancel" @click="onCancel">不需要</view>
						<view class="popup-btn need" @click="onNeed">需要(推荐)</view>
						<view class="popup-btn-close cancel" @click="Shutdown">关机</view>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 无反应弹窗 -->
		<uni-popup ref="popup2" :mask-click="false" :is-mask-click="false" type="center">
			<view class="popup-wrap2">
				<!-- <image class="fixed" src="../../static/image/zixun.png" mode="" @click="skip"></image> -->
				<image class="popup-bg" src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/tips-bg.png" mode="aspectFit" />
				<view class="popup-container">
					<view class="popup-title">
						<image class="popup-img" src="https://yun.shlxkj.info:44300/艾瑞测/小程序/static/img/step-result-normal.png" mode="aspectFit" />
						<view class="popup-text">温馨提示</view>
					</view>
					<view class="popup-content">
						您好，根据本次检测结果，您的尿液抗体筛查结果呈阴性，表明未检测到尿液感染。但需注意，尿液检测存在窗口期（通常为2-6周），若近期有高危行为，建议在窗口期结束后再次检测以完全排除感染风险。如您需要，疾控中心将持续为您提供免费的咨询和检测服务，并严格保护您的个人隐私。
					</view>
					<view class="popup-btn-wrap2">
						<view class="popup-btn-close" @click="closePopup2">关闭</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import store from '@/store';
import TestCheck from '@/pages/home/components/test-check/index.vue';
import Process from '../../components/process/index.vue';
import { ab2hex, sleep, debounce } from '@/utils/util.js';
import {
	GetReleted,
	Getresult,
	DecryptMac,
	CreateReleted,
	ConvertCoordinate,
	UpReagentResult,
	aesDecryptjieguozhi,
	aesDecrypt2,
	AESEncrypt,
	AESDecrypt,
	UpdateReagentResult,
	aesDecryptGetAPiyuzhi,
	InsertSubscribeinform,
	Base64,
	GetReleted_JNC
} from '@/utils/api.js';
const baseSecret = '4B65487561BFC6';
// const HANDLE_0x1800 = '00001800-0000-1000-8000-00805F9B34FB'
// const HANDLE_0x2A00 = '00002A00-0000-1000-8000-00805F9B34FB'
const HANDLE_0x9000 = '00009000-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9001 = '00009001-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9002 = '00009002-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9003 = '00009003-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9004 = '00009004-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9005 = '00009005-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9006 = '00009006-0000-1000-8000-00805F9B34FB';
const HANDLE_0x9007 = '00009007-0000-1000-8000-00805F9B34FB';
const JNA_FFe0 = '0000FFE0-0000-1000-8000-00805F9B34FB';
const JNA_FFe1 = '0000FFE1-0000-1000-8000-00805F9B34FB';
const JNA_FFe2 = '0000FFE2-0000-1000-8000-00805F9B34FB';
let that = null;
export default {
	name: 'Home',
	components: {
		TestCheck,
		Process
	},
	data() {
		return {
			PCBA_Time:15,
			up_type:false,
			PCBA_SetTime: false,
			HFX: '',
			JG: false,
			JG_2: 0,
			weiwancheng: false,
			managePhone: '',
			gps: false,
			processIndex: 1,
			isStartDiscovery: false,
			timer: null,
			checkTimer: null,
			resultTimer: null,
			navHeight: '',
			statusBarHeight: '',
			DetectionType: '',
			times: 0,
			step: 1,
			info: {},
			blueDeviceList: [],
			blueDeviceList_1: [],
			process: [],
			deviceNumber: '', // 设备编号
			scanMac: '', // mac地址
			deviceId: '',
			serviceId: '',
			characteristicId: '',
			key: '',
			new_meg: false,
			collectionStepsData: [
				{
					step: 2,
					name: '采尿'
				},
				{
					step: 3,
					name: '检测'
				}
			],
			stepData: [
				{
					step: 1,
					steps: [
						{
							step: 1,
							imageNum: 1,
							name: '材料检查',
							image: 'step-check(尿检).jpg',
							content: ['请检查电子检测盒、尿杯、滴管等内容物件是否齐全。']
						},
						{
							step: 2,
							imageNum: 2,
							name: '操作准备',
							image: 'step-operate(尿检).jpg',
							content: [
								'1、采集尿液于尿杯中待检；',
								'2、将电子检测盒取出，放在室温中；',
								'3、确认电子检测盒的效期在可使用范围内；',
								'4、在撕口处打开铝箔袋，取出电子检测盒，滴液口向上，平放于桌面。'
							]
						},
						{
							step: 3,
							imageNum: 3,
							name: '开启设备',
							image: 'step-turn-on.png',
							content: ['1、请拔出电池阻断塑料片；', '2、将电子检测盒放在距离手机50cm以内；', '3、观看电子检测盒指示灯是否闪烁。']
						}
						// {
						// 	step: 4,
						// 	imageNum: 4,
						// 	name: '扫码连接',
						// 	image: 'step-connect.png',
						// 	content: ['1、寻找到电子检测盒上二维码；', '2、请点击下方扫一扫；', '3、扫描二维码进行蓝牙连接。']
						// }
					],
					operateName: '扫一扫'
				},
				// 连接失败
				{
					step: 2, // 5
					imageNum: 5,
					name: '连接电子检测盒',
					contentTitle: '请按以下说明进行检查',
					image: 'step-fail.png',
					imageDesc: '连接失败！',
					content: [
						'1、保持电子检测盒在开机状态；',
						'2、检查手机蓝牙，保持开启状态；',
						'3、将手机与电子检测盒尽量靠近，完成蓝牙配对；',
						'4、电子检测盒未连接到其他的手机'
					],
					operateName: '重新扫描'
				},
				// 连接成功
				{
					step: 3, // 6
					imageNum: 6,
					name: '连接电子检测盒',
					image: 'step-success.png',
					custom: true,
					imageDesc: '连接成功！',
					operateName: '下一步'
				},
				{
					step: 4, // 7
					imageNum: 7,
					name: '尿液收集',
					image: 'step-collection(尿检).jpg',
					content: ['采集适量尿液于尿杯中，用滴管吸取适量尿液。'],
					operateName: '下一步'
				},
				{
					step: 5, // 8
					imageNum: 8,
					name: '加样检测',
					image: 'step-add.png',
					content: ['修改文字部分为“用滴管吸取一定量的尿液样本，然后垂直滴入3滴样本（约80uL）到加样孔中。'],
					operateName: '开始检测'
				},
				{
					step: 6, // 9
					imageNum: 9,
					name: '倒计时',
					contentTitle: '请按以下说明进行',
					content: ['1、请保持电子检测盒平放，耐心等待；', '2、请勿退出应用程序；', '3、请勿将手机拿开检测仪超过50cm的距离。'],
					operateName: '',
					timer: 0
				},
				{
					step: 7, // 10
					imageNum: 10,
					name: '检测结果',
					contentTitle: '检测结果说明',
					content: ['检测完成后，请使用碘伏消毒电子检测盒及滴管，并将电子检测盒、滴管以及其他组件放置于废弃物袋中，并密封。'],
					operateName: '',
					result: 0
				}
			],
			OperationDataId: ''
		};
	},
	beforeDestroy() {
		that = null;
		this.resultTimer = null;
		this.timer = null;
	},
	onUnload() {
		this.close();
		this.step = 1;
		this.info = this.stepData[this.step - 1];
	},
	onHide() {
		console.log('用户隐藏了小程序');
		// this.close()
		// this.step = 1
		// this.info = this.stepData[this.step - 1]
	},
	onLoad(op) {
		this.up_type=false,
		this.PCBA_SetTime = false;
		this.weiwancheng = false;
		this.JG = false;
		this.JG_2 = 0;
		this.managePhone = op.phone;
		this.getLocation();
		that = this;

		this.info = this.stepData[this.step - 1];
		//获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
		uni.getSystemInfo({
			success: (e) => {
				// this.compareVersion(e.SDKVersion, '2.5.0')
				let statusBar = 0;
				let customBar = 0;

				// #ifdef MP
				statusBar = e.statusBarHeight;
				customBar = e.statusBarHeight + 45;
				if (e.platform === 'android') {
					// this.$store.commit('SET_SYSTEM_IOSANDROID', false)
					customBar = e.statusBarHeight + 50;
				}
				// #endif

				// #ifdef MP-WEIXIN
				statusBar = e.statusBarHeight;
				// @ts-ignore
				const custom = wx.getMenuButtonBoundingClientRect();
				customBar = custom.bottom + custom.top - e.statusBarHeight;
				// #endif

				// #ifdef APP-PLUS
				console.log('app-plus', e);
				statusBar = e.statusBarHeight;
				customBar = e.statusBarHeight + 45;
				// #endif

				// #ifdef H5
				statusBar = 0;
				customBar = e.statusBarHeight + 45;
				// #endif

				// 这里你可以自己决定存放方式，建议放在store中，因为store是实时变化的
				this.statusBarHeight = statusBar;
				this.navHeight = customBar;
			}
		});
	},
	onShow() {
		if (this.timer && this.step === 6) {
			this.read(HANDLE_0x9007); // 读取结果：0x9007返回的检测结果剩余时间
		}
	},
	methods: {
		closePopup2() {
			this.$refs.popup2.close();
		},
		back: debounce(() => {
			if (that.step === 1) {
				uni.reLaunch({
					url: '/pages/welcome/index'
				});
				return;
			} else if ([3, 6].includes(that.step)) {
				// 扫一扫
				if (that.$store.state.wenjuan_show == true) {
					that.$store.commit('$uStore', {
						name: 'wenjuan_show',
						value: false
					});
					return;
				} else {
					that.step = 1;
					that.info = that.stepData[that.step - 1];
					that.close();
					return;
				}
			} else if (that.step === 7) {
				that.close();
				uni.reLaunch({
					url: '/pages/welcome/index'
				});
				return;
			}
			that.step--;
			that.info = that.stepData[that.step - 1];
		}, 500),
		onConfirm: debounce(async () => {
			console.log(that.step);
			if (that.step === 1) {
				if (that.$store.state.youke == true) {
					uni.showModal({
						title: '提示',
						content: '请先登录！',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/index'
								});
							}
						}
					});
					return
				}
				if (that.gps === false) {
					// console.log('当前未授权定位');
					that.getLocation();
				} else if (that.gps === true) {
					if (that.$store.state.scanMac != '' && that.$store.state.deviceNumber != '') {
						that.scanMac = that.$store.state.scanMac;
						that.deviceNumber = that.$store.state.deviceNumber;
						console.log('外部跳转的scanMac', that.scanMac);
						console.log('外部跳转的deviceNumber', that.deviceNumber);

						// 查询关联关系
						debounce(
							GetReleted({
								devceno: that.deviceNumber,
								IsTask: true
							}).then((res) => {
								console.log(res);
								if (res.code == 801 || res.code == 803) {
									// 没有关联关系
									const city = that.$store.state.vx_city;
									CreateReleted({
										deviceNo: that.deviceNumber,
										macNo: that.scanMac,
										phone: that.$store.state.vx_u_info.phone,
										province: city.province,
										city: city.city,
										county: city.district,
										address: city.address,
										street: city.township,
										type: '尿检微信小程序'
									}).then((res2) => {
										console.log(res2);
										if (res2.code == 200) {
											that.new_meg = true;
											that.initBlue();
										}
									});
								} else {
									// 已有关联
									let phoneNum = res.data.phone;
									Getresult({
										// 获取检测结果
										devceno: that.deviceNumber,
										IsTask: true
									}).then((res2) => {
										console.log(res2);
										if (res2.data.detectionresult == 3) {
											// 检测未完成
											that.weiwancheng = true;
											that.initBlue();
										} else {
											//已经成功上传的数据
											console.log('后台存在数据，直接显示数据', res2.data.detectionresult);
											// let arr = res2.Data
											if (phoneNum == that.$store.state.vx_u_info.phone) {
												let arg1 = res2.data.detectionresult;
												that.step = 7;
												const info = that.stepData[that.step - 1];
												if (arg1 === 1) {
													that.info = Object.assign({}, info, {
														result: arg1,
														operateName: '返回'
													});
													// that.$refs.popup.open('center');
												} else if (arg1 === 0) {
													that.info = Object.assign({}, info, {
														result: arg1,
														operateName: '返回'
													});
													// that.$refs.popup2.open('center');
												} else {
													that.info = Object.assign({}, info, {
														result: arg1,
														operateName: '返回'
													});
												}
											} else {
												uni.showToast({
													title: '本设备已被绑定',
													icon: 'error',
													duration: 2000
												});
												// this.blueDeviceList_1 = []
											}
										}
									});
								}
							})
						);
					} else {
						// 扫码
						uni.scanCode({
							// onlyFromCamera: true,
							success: (res) => {
								console.log(res, '扫一扫成功');
								const result = res.result;
								that.scanDeviceName = result.split(',')[1];
								that.scanMac = result.split(',')[0];
								that.deviceNumber = that.scanDeviceName.padStart(9, '0');
								console.log('scanMac = ', that.scanMac);
								console.log('扫码时的scanMac', that.scanMac);
								console.log('扫码时的scanDeviceName', that.scanDeviceName);
								console.log('扫码时的deviceNumber', that.deviceNumber);

								// 查询关联关系
								debounce(
									GetReleted({
										devceno: that.deviceNumber,
										IsTask: true
									}).then((res) => {
										console.log(res);
										if (res.code == 801 || res.code == 803) {
											// 没有关联关系
											const city = that.$store.state.vx_city;
											CreateReleted({
												deviceNo: that.deviceNumber,
												macNo: that.scanMac,
												phone: that.$store.state.vx_u_info.phone,
												province: city.province,
												city: city.city,
												county: city.district,
												address: city.address,
												street: city.township,
												type: '尿检微信小程序'
											}).then((res2) => {
												console.log(res2);
												if (res2.code == 200) {
													that.new_meg = true;
													that.initBlue();
												}
											});
										} else {
											// 已有关联
											let phoneNum = res.data.phone;
											Getresult({
												// 获取检测结果
												devceno: that.deviceNumber,
												IsTask: true
											}).then((res2) => {
												console.log(res2);
												if (res2.data.detectionresult == 3) {
													// 检测未完成
													that.weiwancheng = true;
													that.initBlue();
												} else {
													//已经成功上传的数据
													console.log('后台存在数据，直接显示数据', res2.data.detectionresult);
													// let arr = res2.Data
													if (phoneNum == that.$store.state.vx_u_info.phone) {
														let arg1 = res2.data.detectionresult;
														that.step = 7;
														const info = that.stepData[that.step - 1];
														if (arg1 === 1) {
															that.info = Object.assign({}, info, {
																result: arg1,
																operateName: '返回'
															});
															// that.$refs.popup.open('center');
														} else if (arg1 === 0) {
															that.info = Object.assign({}, info, {
																result: arg1,
																operateName: '返回'
															});
															// that.$refs.popup2.open('center');
														} else {
															that.info = Object.assign({}, info, {
																result: arg1,
																operateName: '返回'
															});
														}
													} else {
														uni.showToast({
															title: '本设备已被绑定',
															icon: 'error',
															duration: 2000
														});
														// this.blueDeviceList_1 = []
													}
												}
											});
										}
									})
								);
							}
						});
					}
				}
			} else if (that.step === 2) {
				// 扫一扫
				console.log('扫一扫');
				that.step = 1;
				that.info = that.stepData[that.step - 1];
			} else if (that.step === 3) {
				that.step++;
				that.info = that.stepData[that.step - 1];
				console.log('当前', that.info);
			} else if (that.step === 4) {
				that.step++;
				that.info = that.stepData[that.step - 1];
				console.log('当前', that.info);
			} else if (that.step === 5) {
				// 开始检测
				that.getServices(); // 检测是否断开
				if (that.resultTimer) {
					clearInterval(that.resultTimer);
				}
				that.step = 6;
				that.info = that.stepData[that.step - 1];
				that.read(JNA_FFe1);
			} else if (that.step === 7) {
				uni.reLaunch({
					url: '/pages/welcome/index'
				});
				that.close();
			}
		}, 500),
		//软关机
		Shutdown() {
			console.log('关机');
			uni.showModal({
				title: '提示',
				content: '确认关机',
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确认关机');
						that.send_2(HANDLE_0x9004);
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});

			console.log('触发软关机');
		},
		onAdapter() {
			console.log('启动-适配器-监听器');
			uni.onBluetoothAdapterStateChange((e) => {
				console.log('监听到适配器的状态 =》', JSON.stringify(e));
				this.bleAdapter = e;
				if (e.available === false && this.isBack === false) {
					// 扫一扫
					this.bleConnection = false;
					this.step = 1;
					this.info = this.stepData[this.step - 1];
					console.log('适配器不可用');
					// #ifdef MP-WEIXIN
					uni.showToast({
						title: `蓝牙适配器不可用`,
						icon: 'none',
						duration: 2000
					});
					// #endif
					uni.closeBluetoothAdapter({
						success: (res) => {
							console.log('关闭蓝牙适配器成功');
							console.log(res);
						}
					});
				}
			});
		},
		// 初始化
		initBlue() {
			if (this.isStartDiscovery) {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('停止搜索');
						console.log(res);
					}
				});
			}
			uni.openBluetoothAdapter({
				success: (res) => {
					console.log('初始化蓝牙成功', res);
					this.bleAdapter = {
						available: true
					};
					this.onAdapter();
					this.discovery();
				},
				fail: (err) => {
					uni.showModal({
						title: '提示',
						content: '请开启手机蓝牙！',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.closeBluetoothAdapter({
									success: (res) => {
										console.log('关闭蓝牙适配器成功');
										console.log(res);
									}
								});
							}
						}
					});
					console.log('初始化蓝牙失败');
					console.error(err);
				}
			});
		},
		// 开始搜寻附近设备
		discovery() {
			if (!this.bleAdapter.available) {
				this.initBlue();
				return;
			}
			uni.startBluetoothDevicesDiscovery({
				// allowDuplicatesKey: true,
				services: ['0000FFE0-0000-1000-8000-00805F9B34FB'],
				success: (res) => {
					this.isStartDiscovery = true;
					console.log('开始搜索');
					setTimeout(() => {
						if (this.isStartDiscovery) {
							this.stopDiscovery();
							uni.showToast({
								title: '未找到蓝牙设备',
								icon: 'none'
							});
						}
					}, 40000);
					uni.showToast({
						title: '正在寻找蓝牙',
						icon: 'none'
					});
					// 开启监听回调
					this.executeMethods();
					// uni.onBluetoothDeviceFound(this.found)
				},
				fail: (err) => {
					this.isStartDiscovery = false;
					console.log('搜索失败');
					console.error(err);
				}
			});
		},
		// 找到新设备就触发该方法
		found(res) {
			// console.log(res,'found测试');
			if((res.devices[0].advertisServiceUUIDs[0] == '0000FFE0-0000-1000-8000-00805F9B34FB')&&res.devices[0].name!='') {
				if (!this.blueDeviceList.find((item) => item.deviceId === res.devices[0].deviceId)) {
					this.blueDeviceList.push(res.devices[0]);
				}
			}
			console.log('当前设备数组', this.blueDeviceList);
		},
		//附近设备
		executeMethods() {
			// 开启监听回调
			uni.onBluetoothDeviceFound(this.found);
			uni.showToast({
				title: '正在搜索蓝牙...',
				icon: 'none',
				duration: 3000
			});
			// 3秒后执行方法2
			setTimeout(() => {
				this.stopDiscovery();
				console.log(this.blueDeviceList, '找到设备');
				console.log('当前设备编号', this.scanMac);
				this.blueDeviceList.forEach((item) => {
					console.log(item);
					// console.log((item.localName).substring(3),'遍历设备号');
					if (item.name.substring(3) == this.scanMac) {
						this.blueDeviceList_1.push(item);
						console.log('配对成功', this.blueDeviceList_1);
						//开始连接
						this.setConnect();
					}
				});
			}, 3000);
		},
		// 循环设备列表，找到对应的设备
		setConnect() {
			console.log('启动循环');
			this.blueDeviceList_1.forEach((item) => {
				const phonenumber = this.$store.state.vx_u_info.phone;
				console.log('当前手机号', phonenumber);
				debounce(
					GetReleted({
						devceno: this.deviceNumber,
						IsTask: true
					}).then((res2) => {
						if (res2.code == 803 || res2.code == 801) {
							// 没有关联关系
						} else {
							// 有关联关系
							if (res2.data.phone == phonenumber) {
								console.log('绑定机链接');
								uni.showToast({
									title: '正在连接',
									icon: 'success',
									duration: 2000
								});
								this.bleConnect(item);
								this.blueDeviceList_1 = [];
							} else {
								uni.showToast({
									title: '本设备已被绑定',
									icon: 'error',
									duration: 2000
								});
								this.blueDeviceList_1 = [];
							}
						}
					})
				);
			});
		},
		// 连接蓝牙
		async bleConnect(data) {
			uni.createBLEConnection({
				deviceId: data.deviceId,
				success: async (res) => {
					console.log('连接时状态', this.weiwancheng);

					// 2秒后页面切换到（连接成功开始检测）
					// setTimeout(() => {
					// 	if (this.weiwancheng == false) {
					// 		if (this.JG == false) {
					// 			if (this.JG_2 == 1) {
					// 				this.step = 6;
					// 				this.info = this.stepData[this.step - 1];
					// 			} else {
					this.step = 3;
					this.info = this.stepData[this.step - 1];
					// 			}
					// 		}
					// 	}
					// }, 2000);

					this.deviceId = data.deviceId;
					this.serviceId = JNA_FFe0;
					uni.showToast({
						title: `与蓝牙设备连接成功`,
						icon: 'success',
						duration: 2000
					});
					this.getServices();
				},
				fail: (err) => {
					console.log(err);
					if (err.errno === 1509007) {
						uni.showToast({
							title: `蓝牙设备已连接`,
							icon: 'success',
							duration: 2000
						});
						this.getServices();
					} else {
						// 扫一扫
						this.step = 1;
						this.info = this.stepData[this.step - 1];
						console.log('连接失败');
						uni.showToast({
							title: `与蓝牙设备连接失败`,
							icon: 'none',
							duration: 2000
						});
						console.error(err);
					}
				}
			});
		},
		// 停止搜索
		stopDiscovery() {
			uni.stopBluetoothDevicesDiscovery({
				success: (res) => {
					this.isStartDiscovery = false;
					console.log('停止成功');
					console.log(res);
				},
				fail: (err) => {
					console.log('停止失败');
					console.error(err);
				}
			});
		},
		// 获取服务
		getServices() {
			uni.getBLEDeviceServices({
				deviceId: this.deviceId, // 设备ID，在上一步【4】里获取
				success: async (res) => {
					// console.log(this.deviceId + ' getBLEDeviceServices => ', res);
					this.getCharacteristics();
				},
				fail: (err) => {
					console.error(err);
					if (this.checkTimer) {
						clearInterval(this.checkTimer);
						this.checkTimer = null;
					}
					if (this.timer) {
						clearInterval(this.timer);
						this.timer = null;
					}
					if ([-1, 10000, 10002, 10003, 10004, 10005, 10006].includes(err.errCode)) {
						this.close();
						uni.showModal({
							content: '请检查设备是否正常运行，或重新扫描连接，如果设备显示红灯，请更换设备。',
							showCancel: false,
							success(res) {
								if (res.confirm) {
									// 扫一扫
									that.step = 1;
									that.info = that.stepData[that.step - 1];
								}
							}
						});
					}
				}
			});
		},

		// 获取特征值
		getCharacteristics() {
			uni.getBLEDeviceCharacteristics({
				deviceId: this.deviceId, // 设备ID
				serviceId: this.serviceId, // 服务UUID
				success: (res) => {
					// console.log(this.serviceId + 'characteristics =', res);
					this.read(JNA_FFe1);
				},
				fail: (err) => {
					console.error(err);
					if ([10002, 10003, 10006].includes(err.errCode)) {
						this.close();
						uni.showModal({
							content: '请检查设备是否正常运行，或重新扫描连接。',
							showCancel: false,
							success(res) {
								if (res.confirm) {
									// 扫一扫
									that.step = 1;
									that.info = that.stepData[that.step - 1];
								}
							}
						});
					}
				}
			});
		},
		// 监听消息变化
		listenValueChange() {
			if (this.up_type) {
				return;
			}
			uni.onBLECharacteristicValueChange(async (res) => {
				// console.log('onBLECharacteristicValueChange', res)
				// 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
				// console.log('不解密', res.value);
				const resHex = ab2hex(res.value);
				const charId =res.characteristicId
				// console.log('ab2hex ===', resHex)
				if (charId === JNA_FFe1) {
					console.log('JNA', resHex);
					// 先读取JNA_FFe1，以免设备返回04
					// if (that.PCBA_SetTime == false) {
					// 	// that.Send_Qiang(JNA_FFe2, that.PCBA_Time);
					// 	// that.Send_Qiang(JNA_FFe2, 10);
					// 	that.Send_Qiang(JNA_FFe2, 15);
					// }
					if (resHex.substring(0, 2) == '00') {
						console.log('JNA检测未启动,隔5秒后再次读取');
						if (that.weiwancheng == true) {
							that.step = 6;
							that.info = that.stepData[that.step - 1];
						}
						that.times = -1;
						that.resultTimer = setTimeout(function () {
				
							that.clearTimer('resultTimer');
							// that.read(JNA_FFe1);
							that.getServices();
						}, 5000);
					} else if (resHex.substring(0, 2) == '01' && that.up_type == false) {
						console.log('JNA检测已启动,检测倒计时');
						if (that.weiwancheng == true) {
							that.step = 6;
							that.info = that.stepData[that.step - 1];
						}
						that.JG_2 = 1;
						//如果设置为10分钟的话，直接用600秒减去蓝牙返回的时间，就是剩余时间
						let decimalNumber = parseInt(resHex.substring(2, 6), 16); // 将十六进制字符串转换为十进制数
						let data = decimalNumber; // 直接作为秒使用
						let end = Date.now() + (data + 1) * 1000;
					
						that.clearTimer('timer');
						let times = data;
						times = that.PCBA_Time * 60 - parseInt((end - Date.now()) / 1000);
						that.times = times;
						that.timer = setInterval(async () => {
							// times = parseInt((end - Date.now()) / 1000);
							console.log('倒计时', times);
							if (times <= 0) {
								times = 0;
								clearInterval(that.timer);
								that.timer = null;
								// 开始读取过程值
								console.log('倒计时结束', times);
								that.JG = true;
								// that.read(JNA_FFe1);
								that.getServices();
								that.up_type = true;
							} else {
								// that.read(JNA_FFe1);
								that.getServices();
							}
						}, 1000);
					} else if (resHex.substring(0, 2) === '02' || resHex.substring(0, 2) === '04') {
						that.clearTimer('timer');
						that.clearTimer('resultTimer');
						let detectionResult = 0;
						let detectionMessage = '';
						let detectionType = resHex.substring(0, 2);
						let floatValue = 0;
						// 处理JNA检测结果
						if (detectionType === '02') {
							console.log('JNA检测结果', resHex.substring(6, 14));
							let reversed = resHex.substring(6, 14).match(/.{2}/g).reverse().join('');
							// 1. 将 hex 字符串转换为字节数组
							const buffer = new ArrayBuffer(4); // 4 字节表示 32 位浮点数
							const view = new DataView(buffer);
							// 2. 将每个 2 个字符的 hex 转换为字节并写入缓冲区
							for (let i = 0; i < 4; i++) {
								view.setUint8(i, parseInt(reversed.substr(i * 2, 2), 16));
							}
							// 3. 从缓冲区读取 32 位浮点数
							floatValue = view.getFloat32(0, false); // false 表示大端字节序
							console.log('尿检JNA结果转换', floatValue);
							detectionMessage = floatValue >= -0.04 ? '返回' : '返回';
							detectionResult = floatValue >= -0.04 ? 1 : 0;
						} else if (detectionType === '04') {
							// 处理JNA检测异常
							console.log('JNA检测异常');
							detectionMessage = '返回';
							detectionResult = 4;
						}
						that.DetectionType = that.scanMac;
						that.DetectionResult = detectionResult;
						that.Jieguozhi = floatValue.toString();
						// 更新步骤
						that.step = 7;
						const info = that.stepData[that.step - 1];
						that.info = Object.assign({}, info, {
							result: detectionResult,
							operateName: detectionMessage
						});
				
						// 提交上报结果
						const city = that.$store.state.vx_city;
						const res = await UpReagentResult({
							deviceNo: that.deviceNumber,
							macNo: that.scanMac,
							detectionType: that.DetectionType,
							phone: that.$store.state.vx_u_info.phone,
							province: city.province,
							city: city.city,
							county: city.district,
							address: city.address,
							street: city.township,
							detectionResult: detectionResult, // 判断过的数据
							realDetectionResult: detectionResult, // 真实数据
							yuzhi: '',
							jieguozhi: detectionType === '02' ? floatValue.toString() : '', // 如果是02才有 jieguozhi
							type: '尿检微信小程序'
						});
				
						// 上报结果
						if (res.code === 200 || res.code === 801) {
							console.log('上报成功结果 ===》', res.data);
						}
						// 停止监听
						that.stopBluetooth();
					}
				} else if (charId === JNA_FFe2) {
					console.log('JNA_FFe2=>>>>>>>>>>>>', resHex);
					// 5B0D0A070112015D
					if (resHex == '5b0d0a080112015d') {
						// that.read(JNA_FFe1);
							that.getServices();
					} else if (resHex == '5B0D0A070112025D') {
						// that.Send_Qiang(JNA_FFe2, that.PCBA_Time);
						// that.Send_Qiang(JNA_FFe2, 10);
						that.Send_Qiang(JNA_FFe2, 15);
					}
				}
			});
		},
		// aes解密方法
		async aesDecrypt(word, handle) {
			const res = await AESDecrypt({
				Data: word,
				Key: this.key,
				Handle: handle
			});
			if (res.code === 200) {
				return res.data;
			}
		},
		// aes加密方法
		async aesEncrypt(word) {
			const res = await AESEncrypt({
				Data: word,
				Key: this.key
			});
			if (res.code === 200) {
				return res.data;
			}
		},
		// 统一清理定时器
		clearTimer(timerName) {
			if (this[timerName]) {
				clearTimeout(this[timerName]);
				clearInterval(this[timerName]);
				this[timerName] = null;
			}
		},
		// 向设备发送数据
		async send(characteristicId, type = 0) {
			console.log(`写入${characteristicId}，值为${type}`);
			let Data = '';
			if (type === 0) {
				Data = '00000000000000000000000000000000';
			} else {
				Data = '10000000000000000000000000000000';
			}
			const res = await AESEncrypt({
				Data,
				Key: this.key
			});
			// console.log('写入', Data, res.Data);
			if (res.code === 200) {
				const buffer = new ArrayBuffer(res.data);
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId, // 设备ID，在【4】里获取到
					serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
					characteristicId, // 特征值，在【7】里能获取到
					value: buffer,
					success: async (res) => {
						console.log('写入指令发送成功', res);
						await sleep(100);
						await this.getCharacteristics();
					},
					fail: (err) => {
						console.log('写入指令发送失败', err);
					}
				});
			}
		},
		async Send_Qiang(characteristicId, type) {
			let that = this;
			console.log(`写入${characteristicId}，值为${type}`);
			let Data = '';
			if (type === 5) {
				Data = '5B0D0A080102055D';
			} else if (type === 10) {
				Data = '5B0D0A0801020A5D';
			} else if (type === 15) {
				Data = '5B0D0A0801020F5D';
			}
			const buffer = this.hexStringToArrayBuffer(Data);
			console.log(buffer, '命令值');
			uni.writeBLECharacteristicValue({
				deviceId: this.deviceId, // 设备ID，在【4】里获取到
				serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
				characteristicId: '0000FFE2-0000-1000-8000-00805F9B34FB', // 特征值，在【7】里能获取到
				value: buffer,
				success: async (res) => {
					that.PCBA_SetTime = true;
					that.PCBA_Time=type
					console.log('当前倒计时设置为:', that.PCBA_Time);
					console.log('写入JNA_FFe2的0指令发送成功', res);
					await sleep(100);
					that.read(JNA_FFe2);
					await that.getCharacteristics();
				},
				fail: (err) => {
					console.log('写入指令发送失败', err);
				}
			});
		},
		hexStringToArrayBuffer(hexString) {
			const hex = hexString.replace(/\s/g, ''); // 移除空格
			const bytes = new Uint8Array(hex.length / 2);
			for (let i = 0; i < hex.length; i += 2) {
				bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
			}
			return bytes.buffer;
		},
		async send_2(characteristicId) {
			console.log(`写入${characteristicId}`);
			let Data = '';
			Data = '73687574000000000000000000000000';
			const res = await AESEncrypt({
				Data,
				Key: this.key
			});
			let closekey = res.data.toUpperCase();
			console.log(closekey.toUpperCase());
			if (res.code === 200) {
				// 向蓝牙设备发送一个0x00的16进制数据
				// const buffer = new ArrayBuffer(closekey)
				const buffer = this.hexStringToArrayBuffer(closekey);
				console.log(buffer, '命令值');

				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId, // 设备ID，在【4】里获取到
					serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
					characteristicId, // 特征值，在【7】里能获取到
					value: buffer,
					writeType: 'write',
					success: async (res) => {
						this.$refs.popup.close();
						console.log('写入指令发送成功', res);
					},
					fail: (err) => {
						console.log('写入指令发送失败', err);
					}
				});
			}
		},
		// 【11】读取数据
		read(characteristicId) {
			// console.log('read ', this.deviceId, this.serviceId, characteristicId);
			uni.readBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId,
				success: (res) => {
					// console.log('读取指令发送成功')
					// 接受消息的方法
					this.listenValueChange();
				},
				fail: (err) => {
					console.log('读取指令发送失败', err);
				}
			});
		},
		//停止消息监听
		stopBluetooth(characteristicId) {
			// 停止监听蓝牙特征值变化
			uni.offBLECharacteristicValueChange();
			console.log('停止获取蓝牙特征值');
		},
		async close() {
			this.times = 0;
			if (this.resultTimer) {
				clearInterval(this.resultTimer);
				this.resultTimer = null;
			}
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			if (this.checkTimer) {
				clearInterval(this.checkTimer);
				this.checkTimer = null;
			}
			if (this.$refs.testCheck) {
				this.$refs.testCheck.getReset();
			}
			this.$refs.popup.close();
			//断开蓝牙连接
			uni.closeBLEConnection({
				//设备ID
				deviceId: this.deviceId,
				success(res) {
					console.log('断开蓝牙连接', res);
				}
			});
			sleep(1000);
			//关闭蓝牙模块
			uni.closeBluetoothAdapter({
				success(res) {
					console.log('关闭蓝牙模块', res);
				}
			});
			sleep(1000);
		},
		async onCancel() {
			const res = await UpdateReagentResult({
				deviceno: this.deviceNumber,
				phone: this.$store.state.vx_u_info.phone,
				isneedcontact: false
			});
			if (res.code === 200) {
				this.close();
				this.$refs.popup.close();
			} else {
				this.$refs.popup.close();
			}
		},
		async onNeed() {
			const res = await UpdateReagentResult({
				deviceno: this.deviceNumber,
				phone: this.$store.state.vx_u_info.phone,
				isneedcontact: true
			});
			if (res.code === 200) {
				this.close();
				this.$refs.popup.close();
				uni.navigateTo({
					url: '/page_airuice/hospital/index'
				});
			} else {
				this.$refs.popup.close();
				uni.navigateTo({
					url: '/page_airuice/hospital/index'
				});
			}
		},
		// 获取当前位置
		getLocation(tag) {
			uni.getLocation({
				type: 'wgs84',
				success: async (res) => {
					//res.longitude,res.latitude分别为当前经度，纬度
					ConvertCoordinate({
						Locations: [res.longitude, res.latitude].join(',')
					}).then((res) => {
						if (res.code === 200) {
							console.log('定位返回', res.data.regeocode);
							const { province, city, district, township } = res.data.regeocode.addresscomponent;
							const address = res.data.regeocode.formatted_address;
							this.$store.commit('$uStore', {
								name: 'vx_city',
								value: {
									province,
									city,
									district,
									township,
									address
								}
							});
							this.gps = true;
							console.log(this.gps);
						}
					});
				},
				fail: (err) => {
					console.log(err);
					this.gps = false;
					uni.showModal({
						title: '提示',
						content: '使用本设备时，请开启手机定位！',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.openSetting({
									success: function (res) {
										// 在成功回调中判断用户是否已开启位置权限，并进行相应处理
										if (res.authSetting['scope.userLocation']) {
											// 用户已开启位置权限，可以重新调用 uni.getLocation 获取位置信息
											console.log('调用');
										}
									}
								});
							}
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.page {
	width: 100vw;
	height: 100vh;
	width: 100%;
	background-color: #1e64e1;
	position: relative;
	display: flex;
	flex-direction: column;

	.nav-style {
		position: fixed;
		top: 0;
		right: 0;
		left: 0;
		z-index: 1000;
		display: flex;
		padding-left: 23rpx;
		align-items: center;
		justify-content: center;

		.small-logo {
			position: absolute;
			width: 100rpx;
			height: 35rpx;
			left: 45%;
		}

		.back-img {
			width: 36rpx;
			height: 36rpx;
			position: absolute;
			left: 23rpx;
			bottom: 0;
			margin: auto;
		}
	}

	.process-wrap {
		padding-bottom: 50rpx;
		box-sizing: border-box;
	}

	.wrap {
		flex: 1;
		width: 100%;
		margin-top: 36rpx;
		overflow: hidden;
	}

	.popup-wrap {
		width: 615.38rpx;
		height: 1000rpx;
		padding: 42rpx;
		box-sizing: border-box;
		position: relative;
		border-radius: 30rpx;

		.fixed {
			position: fixed;
			top: 20%;
			right: 20rpx;
			z-index: 99;
			width: 60rpx;
			height: 60rpx;
		}

		.popup-bg {
			width: 615.38rpx;
			height: 1000rpx;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 0;
		}

		.popup-container {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
		}

		.popup-title {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			text-align: center;
			margin-top: 34rpx;

			.popup-img {
				width: 130rpx;
				height: 150rpx;
			}

			.popup-text {
				margin-top: 60rpx;
				margin-left: 22rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: #000000;
			}
		}

		.popup-content {
			width: 515rpx;
			margin: 35rpx auto;
			font-size: 27rpx;
			font-weight: 400;
			color: #333333;
			line-height: 40rpx;
			text-align: center;
		}

		.popup-btn-wrap {
			width: 540.38rpx;
			// position: absolute;
			// left: 0;
			// right: 0;
			// bottom: 42rpx;
			margin: auto;
			display: flex;
			justify-content: space-between;
		}

		.popup-btn {
			width: 250rpx;
			height: 85rpx;
			line-height: 85rpx;
			font-size: 28rpx;
			font-weight: 400;
			text-align: center;
			border-radius: 15rpx;
			margin-left: 10rpx;

			&.cancel {
				color: #333333;
				background: #ebebed;
			}

			&.need {
				background: #1e64e1;
				color: #ffffff;
			}
		}

		.popup-btn-close {
			width: 230rpx;
			height: 85rpx;
			line-height: 85rpx;
			font-size: 28rpx;
			font-weight: 400;
			text-align: center;
			border-radius: 15rpx;
			margin-left: 10rpx;

			&.cancel {
				color: #333333;
				background: #ebebed;
			}
		}
	}

	.popup-wrap2 {
		width: 615.38rpx;
		height: 840rpx;
		padding: 42rpx;
		box-sizing: border-box;
		position: relative;
		border-radius: 30rpx;

		.fixed {
			position: fixed;
			top: 20%;
			right: 20rpx;
			z-index: 99;
			width: 60rpx;
			height: 60rpx;
		}

		.popup-bg {
			width: 615.38rpx;
			height: 840rpx;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 0;
		}

		.popup-container {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
		}

		.popup-title {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			text-align: center;
			margin-top: 34rpx;

			.popup-img {
				width: 130rpx;
				height: 150rpx;
			}

			.popup-text {
				margin-top: 60rpx;
				margin-left: 22rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: #000000;
			}
		}

		.popup-content {
			width: 515rpx;
			margin: 35rpx auto;
			font-size: 27rpx;
			font-weight: 400;
			color: #333333;
			line-height: 40rpx;
			text-align: center;
		}

		.popup-btn-wrap2 {
			width: 540.38rpx;
			// position: absolute;
			// left: 0;
			// right: 0;
			// bottom: 42rpx;
			margin: auto;
			display: flex;
			justify-content: center;

			.popup-btn-close {
				width: 230rpx;
				height: 85rpx;
				line-height: 85rpx;
				font-size: 28rpx;
				font-weight: 400;
				text-align: center;
				border-radius: 15rpx;
				// margin-left: 10rpx;
				color: #333333;
				background: #ebebed;
			}
		}
	}
}
</style>
